import { defineComponent, onMounted, type PropType, ref, toRefs, unref } from 'vue'
import { Button, Card, Form, FormItem, Input, InputNumber, Modal, Select, Table, Textarea } from 'ant-design-vue'
import { useDetail } from './use-detail'
import { useForm } from './use-form'
import { BusinessPageTypeEnum } from '@/enums/pageTypeEnum'
import { useColumns } from '@/views/warehouse/sale-return-order/detail/use-detail-columns'
import { orderStatusObj } from '@/views/warehouse/sale-return-order/data'
import { useScanColumns } from '@/views/warehouse/sale-return-order/detail/use-scan-detail-columns'
import { sheLfEnum } from '@/views/base/product/data'

const props = {
  code: {
    type: [String, Number],
    required: false
  },
  orderStatus: {
    type: [String, Number],
    required: false
  },
  businessType: {
    type: String as PropType<BusinessPageTypeEnum>,
    required: true,
    validator: (value: string) => {
      // 检查传入的值是否在枚举的有效值中
      return Object.values(BusinessPageTypeEnum).includes(value as BusinessPageTypeEnum)
    }
  }
}

const DataDetail = defineComponent({
  emits: ['cancelModal', 'confirmModal'],
  props,
  name: 'DataDetail',
  setup(props, ctx) {
    const { meta, state, initForm, getFormValues } = useForm()
    const {
      status,
      createOrUpdate,
      getDataById,
      getShopList,
      getProductOptions,
      getWarehouseList,
      getProductByCode,
      auditOrder,
      getSaleScanDetailList,
      getReturnScanDetailList
    } = useDetail(getFormValues)
    const shopOptionData = ref<any[]>([])
    const productOptionData = ref<any[]>([])
    const warehouseOptionData = ref<any[]>([])
    const saleTableData = ref<any[]>([])
    const scanTableData = ref<any[]>([])
    const returnTableData = ref<any[]>([])
    const productCodeDisplay = ref(false)
    const saleTotalAmount = ref(0)
    const returnTotalAmount = ref(0)

    const deleteRow = (key: any, isSale: boolean) => {
      resetTotalAmount(isSale)
      if (isSale) {
        saleTableData.value?.splice(key, 1)
      } else {
        returnTableData.value?.splice(key, 1)
      }
    }

    const lookProductCode = async (code: String, isSale: boolean) => {
      productCodeDisplay.value = true
      if (isSale) {
        scanTableData.value = await getSaleScanDetailList(code)
      } else {
        scanTableData.value = await getReturnScanDetailList(code)
      }
    }

    const cancelModalClick = () => {
      productCodeDisplay.value = false
    }

    const confirmModalClick = () => {
      productCodeDisplay.value = false
    }

    const addRow = (isSale: boolean) => {
      if (isSale) {
        saleTableData.value?.push({})
      } else {
        returnTableData.value?.push({})
      }
    }

    const setProductToTableData = async (code: string, index: number, isSale: boolean) => {
      const selectProduct = await getProductByCode(code)
      if (isSale) {
        saleTableData.value[index].productCode = selectProduct.code
        saleTableData.value[index].productName = selectProduct.name
        saleTableData.value[index].productUniqueCode = selectProduct.productUniqueCode
        saleTableData.value[index].productSpecification =
          selectProduct.specificationNumber + selectProduct.specificationName
        saleTableData.value[index].productPacking = selectProduct.packingNumber + selectProduct.packingName
        let shelfLifeUnitStr = ''
        sheLfEnum.forEach(model => {
          if (model.value == selectProduct.shelfLifeUnit) {
            shelfLifeUnitStr = model.label
          }
        })
        saleTableData.value[index].productShelfLife = selectProduct.shelfLife + shelfLifeUnitStr
        saleTableData.value[index].productPrice = selectProduct.supplyPrice
      } else {
        returnTableData.value[index].productCode = selectProduct.code
        returnTableData.value[index].productName = selectProduct.name
        returnTableData.value[index].productUniqueCode = selectProduct.productUniqueCode
        returnTableData.value[index].productSpecification =
          selectProduct.specificationNumber + selectProduct.specificationName
        returnTableData.value[index].productPacking = selectProduct.packingNumber + selectProduct.packingName
        let shelfLifeUnitStr = ''
        sheLfEnum.forEach(model => {
          if (model.value == selectProduct.shelfLifeUnit) {
            shelfLifeUnitStr = model.label
          }
        })
        returnTableData.value[index].productShelfLife = selectProduct.shelfLife + shelfLifeUnitStr
        returnTableData.value[index].productPrice = selectProduct.supplyPrice
      }
    }

    // 更新总金额
    const resetTotalAmount = (isSale: boolean) => {
      if (isSale) {
        saleTotalAmount.value = 0
        for (let i = 0; i < saleTableData.value.length; i++) {
          saleTotalAmount.value += saleTableData.value[i].productPrice * saleTableData.value[i].productNumber
        }
      } else {
        returnTotalAmount.value = 0
        for (let i = 0; i < returnTableData.value.length; i++) {
          returnTotalAmount.value += returnTableData.value[i].productPrice * returnTableData.value[i].productNumber
        }
      }
    }

    const { getColumns, tableColumns } = useColumns(
      deleteRow,
      setProductToTableData,
      resetTotalAmount,
      lookProductCode,
      props.orderStatus,
      productOptionData,
      props.businessType
    )

    const { getScanColumns, scanTableColumns } = useScanColumns()

    const checkSimple = (index: any, isSale: boolean) => {
      if (isSale) {
        if (!saleTableData.value[index].productCode) {
          window.alert('请选择产品')
          return false
        }
      } else {
        if (!returnTableData.value[index].productCode) {
          window.alert('请选择产品')
          return false
        }
      }
      return true
    }

    const checkFormData = () => {
      if (!state.detailForm.shopCode) {
        window.alert('请选择门店')
        return false
      }
      if (saleTableData.value?.length <= 0 && returnTableData.value?.length <= 0) {
        window.alert('销售数据或退货数据至少有一条数据')
        return false
      }
      for (let i = 0; i < saleTableData.value.length; i++) {
        if (!checkSimple(i, true)) {
          return false
        }
      }
      for (let i = 0; i < returnTableData.value.length; i++) {
        if (!checkSimple(i, false)) {
          return false
        }
      }
      return true
    }

    const handleCommit = async () => {
      if (checkFormData()) {
        state.detailForm.saleOrderDetailFormList = saleTableData.value
        state.detailForm.returnOrderDetailFormList = returnTableData.value
        for (let i = 0; i < shopOptionData.value.length; i++) {
          if (state.detailForm.shopCode === shopOptionData.value[i].value) {
            state.detailForm.shopName = shopOptionData.value[i].label
          }
        }
        for (let i = 0; i < warehouseOptionData.value.length; i++) {
          if (state.detailForm.warehouseCode === warehouseOptionData.value[i].value) {
            state.detailForm.warehouseName = warehouseOptionData.value[i].label
          }
        }
        await createOrUpdate()
        initForm()
        ctx.emit('confirmModal')
      }
    }

    const resetForm = () => {
      initForm()
      ctx.emit('cancelModal')
    }

    onMounted(async () => {
      await fetchData()
      shopOptionData.value = await getShopList()
      productOptionData.value = await getProductOptions()
      warehouseOptionData.value = await getWarehouseList()
      resetTotalAmount(false)
      resetTotalAmount(true)
    })

    const fetchData = async () => {
      if (props.businessType === BusinessPageTypeEnum.UPDATE || props.businessType === BusinessPageTypeEnum.DETAIL) {
        // 查询值
        state.detailForm = await getDataById(props.code)
        saleTableData.value = state.detailForm.saleOrderDetailFormList
        returnTableData.value = state.detailForm.returnOrderDetailFormList
      }
    }

    return {
      ...toRefs(props),
      ...toRefs(state),
      ...toRefs(status),
      ...toRefs(meta),
      shopOptionData,
      warehouseOptionData,
      getColumns,
      tableColumns,
      getScanColumns,
      scanTableColumns,
      saleTableData,
      scanTableData,
      returnTableData,
      saleTotalAmount,
      returnTotalAmount,
      productCodeDisplay,
      cancelModalClick,
      confirmModalClick,
      auditOrder,
      addRow,
      deleteRow,
      handleCommit,
      resetForm
    }
  },
  render() {
    const {
      code,
      businessType,
      detailForm,
      rules,
      shopOptionData,
      warehouseOptionData,
      getColumns,
      tableColumns,
      getScanColumns,
      scanTableColumns,
      saleTableData,
      scanTableData,
      returnTableData,
      saleTotalAmount,
      returnTotalAmount,
      productCodeDisplay,
      cancelModalClick,
      confirmModalClick,
      auditOrder,
      addRow,
      handleCommit,
      resetForm
    } = this
    // @ts-ignore
    return (
      <>
        <Card>
          <Form
            ref='detailFormRef'
            model={detailForm}
            rules={rules}
            labelCol={{ span: 3 }}
            wrapperCol={{ span: 17 }}
            style={{ width: '80%' }}
            onFinish={handleCommit}
          >
            <FormItem label='目标门店' name='shopCode'>
              <Select
                disabled={businessType !== BusinessPageTypeEnum.ADD}
                mode='single'
                v-model={[detailForm.shopCode, 'value']}
                options={shopOptionData}
              />
            </FormItem>
            <FormItem label='发货仓库' name='shopCode'>
              <Select
                disabled={businessType !== BusinessPageTypeEnum.ADD}
                mode='single'
                v-model={[detailForm.warehouseCode, 'value']}
                options={warehouseOptionData}
              />
            </FormItem>
            <FormItem label='快递单号' name='expressNumber'>
              <Input
                disabled={
                  businessType === BusinessPageTypeEnum.DETAIL || orderStatusObj[3].value === detailForm.orderStatus
                }
                mode='single'
                v-model={[detailForm.expressNumber, 'value']}
              />
            </FormItem>
            <FormItem label='已付款金额' name='paymentAmount'>
              <InputNumber
                disabled={
                  businessType === BusinessPageTypeEnum.DETAIL || orderStatusObj[3].value === detailForm.orderStatus
                }
                mode='single'
                v-model={[detailForm.paymentAmount, 'value']}
              />
            </FormItem>
            <FormItem label='销售总金额' name='saleTotalAmount'>
              <Input disabled mode='single' v-model={[saleTotalAmount, 'value']} />
            </FormItem>
            <FormItem label='退货总金额' name='returnTotalAmount'>
              <Input disabled mode='single' v-model={[returnTotalAmount, 'value']} />
            </FormItem>
            <FormItem label='备注' name='description'>
              <Textarea
                disabled={businessType === BusinessPageTypeEnum.DETAIL}
                v-model={[detailForm.remark, 'value']}
                maxlength={200}
                rows={3}
              />
            </FormItem>
            <Card title={'销售数据'}>
              {businessType != BusinessPageTypeEnum.DETAIL && orderStatusObj[3].value !== detailForm.orderStatus && (
                <Button type='primary' onClick={() => addRow(true)}>
                  新增一行
                </Button>
              )}
              <br />
              <Table
                rowKey='id'
                columns={
                  businessType != BusinessPageTypeEnum.DETAIL
                    ? tableColumns
                    : tableColumns.slice(0, tableColumns.length - 1)
                }
                style={{ width: '1000px' }}
                dataSource={unref(saleTableData)}
                pagination={false}
                bordered
              >
                {{
                  bodyCell: ({ column, record, index }) => getColumns(column, record, index, true)
                }}
              </Table>
            </Card>
            <Card title={'退货数据'}>
              {businessType != BusinessPageTypeEnum.DETAIL && orderStatusObj[3].value !== detailForm.orderStatus && (
                <Button type='primary' onClick={() => addRow(false)}>
                  新增一行
                </Button>
              )}
              <br />
              <Table
                rowKey='id'
                columns={
                  businessType != BusinessPageTypeEnum.DETAIL
                    ? tableColumns
                    : tableColumns.slice(0, tableColumns.length - 1)
                }
                style={{ width: '1000px' }}
                dataSource={unref(returnTableData)}
                pagination={false}
                bordered
              >
                {{
                  bodyCell: ({ column, record, index }) => getColumns(column, record, index, false)
                }}
              </Table>
            </Card>
            <FormItem wrapperCol={{ span: 12, offset: 12 }}>
              {businessType === BusinessPageTypeEnum.UPDATE && orderStatusObj[3].value !== detailForm.orderStatus && (
                <Button
                  type='primary'
                  style={'margin-right: 10px'}
                  onClick={async () => {
                    const result = await auditOrder(code, { updateStatus: 4 })
                    if (result === false) {
                      window.alert('订单还没签收，无法审核')
                    }
                  }}
                >
                  审核
                </Button>
              )}
              {businessType === BusinessPageTypeEnum.DETAIL && <Button onClick={resetForm}>返回</Button>}
              {businessType !== BusinessPageTypeEnum.DETAIL && (
                <>
                  <Button type='primary' htmlType='submit'>
                    提交
                  </Button>
                  <Button style={{ marginLeft: '12px' }} onClick={resetForm}>
                    取消
                  </Button>
                </>
              )}
            </FormItem>
          </Form>
          <Modal open={productCodeDisplay} title={'产品码'} onCancel={cancelModalClick} onOk={confirmModalClick}>
            <Table
              rowKey='id'
              columns={scanTableColumns}
              style={{ width: '450px' }}
              dataSource={unref(scanTableData)}
              pagination={false}
              bordered
            >
              {{
                bodyCell: ({ column, record }) => getScanColumns(column, record)
              }}
            </Table>
          </Modal>
        </Card>
      </>
    )
  }
})
export default DataDetail
